﻿using SuddenDeath.Domain.Services.FileManager.elFinder.Responses;
using SuddenDeath.Domain.Services.FileManager.elFinder.Utils;

namespace SuddenDeath.Domain.Services.FileManager.elFinder.Commands
{
    public class Rename : ICommand
    {
        public string Target { get; set; }

        public string Current { get; set; }

        public string Name { get; set; }

        public Rename(string current, string target, string name)
        {
            Target = target;
            Current = current;
            Name = name;
        }

        #region ICommand Members       

        public Response Execute()
        {
            var path = DirectoryUtils.GetRelativePathByHash(Current, Configuration.Configuration.RootPath);

            var toRename = DirectoryUtils.GetFilePathByHash(Target, Configuration.Configuration.RootPath);

            var isDir = false;

            try
            {
                System.IO.File.Move(toRename, path + "/" + Name);
            }
            catch
            {
                System.IO.Directory.Move(toRename, path + "/" + Name);
                isDir = true;
            }

            var folder = new Folder(path);

            var response = new DirectoryResponse { cwd = folder.Cwd, cdc = folder.Contents };

            if (isDir)
            {
                response.tree = folder.Tree;
            }

            return response;
        }

        #endregion
    }
}
